﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.IO;

class RC4Class
{
    public static void RC4Method(ref Byte[] bytes, Byte[] key)
    {
        Byte[] s = new Byte[256];
        Byte[] k = new Byte[256];
        Byte temp;
        int i, j;

        for (i = 0; i < 256; i++)
        {
            s[i] = (Byte)i;
            k[i] = key[i % key.GetLength(0)];
        }

        j = 0;
        for (i = 0; i < 256; i++)
        {
            j = (j + s[i] + k[i]) % 256;
            temp = s[i];
            s[i] = s[j];
            s[j] = temp;
        }

        i = j = 0;
        for (int x = 0; x < bytes.GetLength(0); x++)
        {
            i = (i + 1) % 256;
            j = (j + s[i]) % 256;
            temp = s[i];
            s[i] = s[j];
            s[j] = temp;
            int t = (s[i] + s[j]) % 256;
            bytes[x] ^= s[t];
        }
    }

    public static byte[] ReadFile(FileStream fs)
    {
        byte[] result = new byte[fs.Length];        
        using (fs)
        {
            int offset = 0;
            while (true) 
            {
                int readLength = fs.Read(result, offset, (int)fs.Length - offset);
                offset += readLength;
                if (readLength == 0)
                {
                    break;
                }
            }
        }
        return result;
    }

    static void Main()
    {
        FileStream fileInput = new FileStream("fileToEncrypt.txt", FileMode.Open);
        byte[] content = ReadFile(fileInput);
        byte[] key = { 9, 17, 32, 36, 20, 24 };
        Console.WriteLine("Before encrypt: {0}",Encoding.UTF8.GetString(content));
        RC4Method(ref content, key);        
        Console.WriteLine("After encrypt: {0}",Encoding.UTF8.GetString(content));
        RC4Method(ref content, key);
        Console.WriteLine("After decrypt: {0}",Encoding.UTF8.GetString(content));
    }
}
